app.controller('publication', function ($scope, $http) {

    var token = localStorage.getItem('token');
    var thisUserId = sessionStorage.getItem('thisUserId');
    //判断有无证书
    if (!token) {
        $.toast('请先登录');
        location.href = '#login';
        return;
    }

    //动态对象
    $scope.dynamic = {};

    //添加动态
    $scope.addDynamic = function () {
        var dynamicImgString = "";
        //判断是否上传有图片
        if ($scope.dynamicImgList.length > 0) {
            //按规则将图片数组转化为string
            for (var i = 0; i < $scope.dynamicImgList.length; i++) {
                if (i == $scope.dynamicImgList.length - 1) {
                    dynamicImgString = dynamicImgString + $scope.dynamicImgList[i];
                } else {
                    dynamicImgString = dynamicImgString + $scope.dynamicImgList[i] + ',';
                }
            }

        }
        var dynamic = {
            dynamicTitle: $scope.dynamic.dynamicTitle,
            dynamicContent: $scope.dynamic.dynamicContent,
            dynamicImg: dynamicImgString
        };

        $.showPreloader('请稍候');
        $http({
            method: 'post',
            url: app.netPath + '/dynamic/add/adynamic',
            headers: {Authorization: token, 'Content-Type': 'application/json'},
            data: dynamic
        }).then(function (res) {
            $.hidePreloader();
            console.log(res.data);
            if (!res.data.error) {
                location.href = '#reflection'
                $.toast('发布思考成功');
            }
            else {
                $.toast(res.data.msg)
            }
        }, function () {
            $.hidePreloader();
            $.toast('网络走丢了！')
        })
    };

    // 定义集合存储动态上传图片
    $scope.dynamicImgList = [];

    //单次提交图片的函数
    //参数为传入的一个文件类型input
    $scope.img_upload = function (files) {

        console.log('ready to upload img.');

        if (!token) {
            return;
        }

        if (!files || !files[0]) {
            console.log('文件为空');

            return;
        }

        //规定上传到服务器图片的大小
        var needHeight = 300;
        var needWidth = 300;

        //规定略缩图大小
        var smallWidth = needWidth * 0.33;

        //FileReader用来读取本地文件
        var reader = new FileReader();

        //实例化图片用于被加载在画布上
        var img = new Image();

        // 破除一个协议
        img.setAttribute("crossOrigin", 'Anonymous');

        //声明一个画布对象，当图片上传成功后添加到数组中便于显示
        var img_obj = {};

        //获取当前时间戳作为画布唯一id
        img_obj.id = new Date().getTime();

        //自动刷新双向绑定，预防双向绑定失效
        $scope.$digest();

        //获取预览画布
        var canvas = document.createElement('canvas');
        canvas.width = needWidth;
        canvas.height = needHeight;


        //控制略缩图大小
        canvas.style.width = smallWidth + 'px';

        var ctx = canvas.getContext("2d");

        //当图片加载完毕执行动作
        reader.onload = function () {

            // 通过 reader.result 来访问生成的 DataURL
            img.src = reader.result;

            img.onload = function () {

                //获取图片的高宽
                var width = img.width;
                var height = img.height;

                //获取需要使用的矩形图片区域
                var real_width = width * needHeight / needWidth > height ? height * needWidth / needHeight : width;
                var real_height = width > height * needWidth / needHeight ? height : width * needHeight / needWidth;

                //console.log('need:'+real_width+' '+real_height);
                //console.log('real:'+width+' '+height);

                //定位使图片居中
                var img_x = (width - real_width) / 2;
                var img_y = (height - real_height) / 2;

                //在画布上渲染头像预览
                ctx.drawImage(img, img_x, img_y, real_width, real_height, 0, 0, needWidth, needHeight);

                //将画布渲染的图像转换为base64字符串储存在data中
                var data = canvas.toDataURL();
                // console.log(data);


                //发送POST请求
                $http({

                    method: 'post',
                    url: app.netPath + "/dynamic/image-upload",
                    headers: {'Authorization': token},
                    data: data

                }).then(function (res) {
                    console.log(res.data);

                    if (!res.data.error) {
                        console.log(res.data.data);
                        //封装路径显示图片
                        $scope.dynamicImg = app.netPath + '/resources/dynamicImg/' + res.data.data;
                        //当图片上传成功添加图片显示节点
                        $("#dynamicImgList").before("<li class='dynamicImgLi' onclick='delete()'> <a class='btn-upload not'> <div class='list'> <img class='dynamicImg' src='" + $scope.dynamicImg + "'> </div> </a></li>");
                        //存入刚上传成功的图片名称
                        $scope.dynamicImgList.push(res.data.data);

                        //监听点击事件（移除不想上传的图片节点）
                        $('.dynamicImgLi').bind('click', function () {
                            //得到当前点击的li节点位于集合中的顺序
                            var i = $(this).index();
                            //移除所点击的图片
                            $('.dynamicImgLi')[i].remove();
                            //相应图片数组中取出想应值
                            $scope.dynamicImgList.splice(i, 1);
                        })
                    } else {
                        $.toast('错误代码：' + res.data.error + "," + res.data.msg);
                    }


                }, function () {
                    $scope.img_del(index);
                    $.toast('网络或设置错误');
                });
                //清除原来画布内容
                ctx.clearRect(0, 0, needWidth, needHeight);
            };


        };


        //加载选中的图片
        reader.readAsDataURL(files[0]);
    };

});
